package com.vcredit.creditcat.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.CustIsRealEnum;
import com.vcredit.creditcat.manager.CreditCatProcessManager;
import com.vcredit.creditcat.model.AuthItem;
import com.vcredit.creditcat.model.AuthJd;
import com.vcredit.creditcat.model.AuthLog;
import com.vcredit.creditcat.persistence.AuthJdExtMapper;
import com.vcredit.creditcat.persistence.base.AuthJdMapper;

/**
 * 
 **/
@Service
public class AuthJdService {
	@Autowired
	private AuthJdMapper mapper;
	@Autowired
	private AuthJdExtMapper extMapper;
	@Autowired
	private CreditCatProcessManager creditCatProcessManager;
	@Autowired
	private AuthLogService authLogService;

	public void insert(AuthJd obj) {
		mapper.insert(obj);
	}

	public void update(AuthJd obj) {
		mapper.update(obj);
	}

	public List<AuthJd> findAll() {
		return mapper.findAll();
	}

	public List<AuthJd> find(AuthJd obj) {
		return mapper.find(obj);
	}

	public AuthJd findByProcessId(Long processId) {
		AuthJd param = new AuthJd();
		param.setProcessId(processId);
		List<AuthJd> list = find(param);
		if (!list.isEmpty())
			return list.get(0);
		return null;
	}

	public List<AuthJd> findUnCrawl() {
		return extMapper.findUnCrawl();
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateCreditJd(AuthJd param) throws Exception {
		AuthJd authJd = findByProcessId(param.getProcessId());
		if (null != authJd) {
			param.setJdProccessId(authJd.getJdProccessId());
			update(param);
		} else {
			insert(param);
		}
		if (null != param.getIsReal() &&  CustIsRealEnum.Yes.getCode() == (param.getIsReal())) {
			creditCatProcessManager.itemDone(new AuthItem(AuthItemEnum.JINGDONG.getCode()), authJd.getProcessId());
			authLogService.insert(new AuthLog(param.getProcessId(), param.getCust().getCustId(),
					AuthItemEnum.JINGDONG.getCode(), param.getExpiredTime(), new Date()));

		}
	}

	public void resetStatus(AuthJd param) {
		update(param);
	}
}